import { Component, OnInit, HostListener, ViewChild, ElementRef, Injector } from '@angular/core';
import { _HttpClient, SettingsService } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd';
import { ProductService } from '../../../service/prod/product.service';
import { CommService } from '../../../service/comm/comm.service';
import { ServiceResult, Constant } from '@core/constant';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { CartService } from 'app/service/cart/cart.service';
import { BaseController } from '@shared/base-controller';
import { inject } from '@angular/core/testing';
import { UserService } from '../../../service/user/user.service';

declare var $: any;

@Component({
  selector: 'order-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.less']
})
export class OrderProductsComponent extends BaseController implements OnInit {

  q: any = {
    pageSize: 10,
    pageNumber: 0, 
    status: '1',  
    productCd: null
  };
  effect = 'scrollx';
  list: {[proname: string]: any}[] = [];
  loading = false;
  userGroups = [];
  
  brandLines = [];
  categorys = [];
  seasons = [];
  imgSuffix = '';
  defaultUrl = './assets/tmp/img/dummy.png';  
  disableBrands = [];

  changeUserGroup(status: boolean, idx: number) {
    if (idx === 0) {
      this.userGroups.map(i => (i.value = status));
    } else {
      this.userGroups[idx].value = status;
    }
    this.onScroll(false);
  }

  changeBrand(status: boolean, idx: number) {
    if (idx === 0) {
      this.brandLines.map(i => (i.value = status));
    } else {
      this.brandLines[idx].value = status;
    }
    this.onScroll(false);
  }

  changeCategory(status: boolean, idx: number) {
    if (idx === 0) {
      this.categorys.map(i => (i.value = status));
    } else {
      this.categorys[idx].value = status;
    }
    this.onScroll(false);
  }

  changeSeason(status: boolean, idx: number) {
    if (idx === 0) {
      this.seasons.map(i => (i.value = status));
    } else {
      this.seasons[idx].value = status;
    }
    this.onScroll(false);
  }
  // endregion

  constructor(private http: _HttpClient, 
    public msg: NzMessageService,
    private prodService: ProductService, 
    private comm: CommService,
    private cartService: CartService,
    public injector: Injector ,
    private cnt: Constant,
    private setting: SettingsService,
    private userServ: UserService
  ) {
    super(injector);
  }
  addBtn = false;
  cartBtn = false;
  currency = null;
  level = 'FIRST';

  init() {
    this.addBtn = this.getAuths(this.cnt.authKey.cart.ADD_BTN);
    this.cartBtn = this.getAuths(this.cnt.authKey.cart.CART_BTN);
    this.imgSuffix = this.comm.getGoodsUrl();
    this.loadUserGroup();
    this.loadCategorys();
    this.loadBrandLines();
    this.loadSeasons();    
    this.onScroll(false);
    this.currency = this.setting.user.currency;

      
    if (this.setting.user.isManager) {
      this.level = 'FIRST';
    } else if (this.setting.user.level === 'FIRST') {
      this.level = 'FIRST';
    } else {
      this.level = 'OTHER';
    }
  }

  ngOnInit() {
    this.init();
  }

  _onReuseInit() {
    this.init();
  }

  // 加载产品季节
  loadSeasons() {
    this.seasons = [];
    this.comm.getSeasons().subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.status === 200) {
        this.seasons.push({ id: 0, text: 'ALL', value: false });
        for (const row of ret['data']['rows']) {
            this.seasons.push({ id: row.value, text: (row.labelEnUs).toUpperCase(), value: false });
        }                                   
      }
    })
  }

  // 加载品牌分类
  loadCategorys() {
    this.categorys = [];
    this.comm.getCategory().subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.status === 200) {
        this.categorys.push({ id: 0, text: 'ALL', value: false });
        for (const row of ret['data']['rows']) {
            this.categorys.push({ id: row.value, text: (row.labelEnUs).toUpperCase(), value: false });
        }                                   
      }
    })
  }

  // 加载品项列表
  loadBrandLines() {
    this.brandLines = [];
    this.comm.getBrandLine().subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.status === 200) {
        this.brandLines.push({ id: 0, text: 'ALL', value: false });
        for (const row of ret['data']['rows']) {
            this.brandLines.push({ id: row.value, text: (row.labelEnUs).toUpperCase(), value: false });
        }                       
      }
    })
  }
  
  loadUserGroup() {
    this.userGroups = [];
    this.comm.getUserGroup().subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.status === 200) {
          this.userGroups.push({ id: 0, text: 'ALL', value: false });
          for (const row of ret['data']['rows']) {
              this.userGroups.push({ id: row.value, text: (row.labelEnUs).toUpperCase(), value: false });
          }                                   
      }
    })
  }

  
 
  hasMore = true; 
  onScroll(append): void {    
    if (this.loading) { 
      return;
    }
    this.loading = true;
    if (append) {
      this.q.pageNumber = this.q.pageNumber + 1;
    } else {    
      this.list = [];
      this.q.pageNumber = 1;
      this.hasMore = true;
    }
    if (this.hasMore) {
      this.http.get(this.prodService.list2(), this.preHandle()).subscribe((res: any) => {        
        if (res.data.rows.length == 0 || res.data.rows.length < this.q.pageSize) {
          this.hasMore = false;
        } else {
          this.hasMore = true;
        }
        if (append) {
          this.list = this.list.concat(res.data.rows);
        } else {
          this.list = res.data.rows;
        }
        this.loading = false;        
      });
    } else {
      this.loading = false;
    }  
  }

  preHandle() {
    let tmpBrands = [];
    let tmpUserGroups = [];
    let tmpSeasons = [];
    let tmpCategorys = [];
    
    this.brandLines.filter(i => {
      return (i.text != '全部' && i.text != 'ALL') && i.value;
    }).forEach(v => {
      tmpBrands.push(v.id);
    });

    this.userGroups.filter(i => {
      return (i.text != '全部' && i.text != 'ALL') && i.value;
    }).forEach(v => {
      tmpUserGroups.push(v.id);
    });

    this.seasons.filter(i => {
      return (i.text != '全部' && i.text != 'ALL') && i.value;
    }).forEach(v => {
      tmpSeasons.push(v.id);
    });

    this.categorys.filter(i => {
      return (i.text != '全部' && i.text != 'ALL') && i.value;
    }).forEach(v => {
      tmpCategorys.push(v.id);
    });

    return {
      status: '1',
      batchUserGroup: tmpUserGroups.toString(),
      batchBrandLine: tmpBrands.toString(),
      batchSeason: tmpSeasons.toString(),
      batchCategory: tmpCategorys.toString(),
      productCd: this.q.productCd,
      pageSize: this.q.pageSize,
      pageNumber: this.q.pageNumber
    }
  }

  minCount(prod) {
    if (prod.cart === undefined) {
      prod.cart = 0;
    }
    prod.cart--;
    if (prod.cart < 0) {
      prod.cart = 0;
    }
    this.doCart(prod);
  }

  addCount(prod) {
    if (prod.cart === undefined) {
      prod.cart = 0;
    }
    prod.cart++;
    this.doCart(prod);    
  }
 
  doCart(prod) {
    this.cartService.modifyCart(prod.productCd, prod.cart).pipe(
      catchError(err => {
        return of(err)
      })
    ).subscribe(data => {
      if (data.status !== 200) {
        this.msg.error(data.message);
      }
    })
  }

  modifyCart(prod, v) {
    this.cartService.modifyCart(prod.productCd, v).pipe(
      catchError(err => {
        return of(err)
      })
    ).subscribe(data => {
      if (data.status !== 200) {
        this.msg.error(data.message);
      }
    })
  }


  selectProd(styleRow, event) {
    styleRow.index = event;
  }

  selectProduct: {[propName: string]: any;} = {}
  selectUrl = null;
  visible = false;
  price = 0;
  stock = '';  

  view(record) {
    this.price = record.realPrice;
    this.stock = record.gmStockSap >= 10 ? 'Sufficient' : (record.gmStockSap > 0 ? 'Limited' : 'Out of stock');
    this.prodService.getProduct(record.id).pipe(
      catchError(err => {                             
        return of(err);
      })
    ).subscribe(data => {      
      this.selectProduct = data.data;              
      // 拼接图片地址
      this.selectUrl = this.comm.getGoodsUrl() + this.selectProduct.img;
      this.visible = true;        
    })
   
  }

  close(): void {
    this.visible = false;
  }
}
